/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_zml.htm
 *
 * Zhiqim Zml is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.zml.loader;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import org.zhiqim.kernel.model.maps.HashMapSV;
import org.zhiqim.kernel.util.Resources;

/**
 * ZML类目录检查，所有包含*.zml文件的包，当前采用11秒内不检查
 * TODO 在1.4版本后续中进行优化
 *
 * @version v1.0.0 @author zouzhigang 2016-7-13 新建与整理
 */
public class ClassZmlWatcher
{
    private final Class<?> loadClass;
    private final String pathPrefix;
    private final HashMapSV<long[]> modifiedMap;
    
    public ClassZmlWatcher(Class<?> loadClass, String pathPrefix)
    {
        this.loadClass = loadClass;
        this.pathPrefix = pathPrefix;
        this.modifiedMap = new HashMapSV<>();
    }
    
    public long getLastModified(String path)
    {
        long[] value = modifiedMap.get(path);
        if (value != null)
        {
            if (System.currentTimeMillis() - value[1] < 11 * 1000)
                return value[0];//11秒内不再检查更新
        }
        
        URL url = Resources.getResource(loadClass, pathPrefix + path);
        if (url == null)
        {//未找到，直接返回-1
            modifiedMap.remove(path);
            return -1;
        }
        
        try
        {
            URLConnection conn = url.openConnection();
            long lastModified = conn.getLastModified();
            modifiedMap.put(path, new long[]{lastModified, System.currentTimeMillis()});
            return lastModified;
        }
        catch (IOException e)
        {
            modifiedMap.remove(path);
            return -1;
        }
    }
}
